package com.example.jta.service;

import com.example.jta.dao.log.EventLogDao;
import com.example.jta.dao.order.UserOrderDao;
import com.example.jta.domain.log.EventLog;
import com.example.jta.domain.order.UserOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;

/**
 * Created by caibosi on 2018-07-25.
 */
@Component
public class OrderService {

    @Autowired
    UserOrderDao userOrderDao;

    @Autowired
    EventLogDao eventLogDao;

    /**
     * atomikos是事务管理器
     * postgres 默认不是分布式事务
     * 切记修改postgres.conf的参数max_prepared_transactions，默认是0，设置大于0
     * 每次提交的时候，会把prepare commit提交到本地磁盘存储
     * 然后断开
     */
    @Transactional
    public void newOrder(String userId, String productCode, int quantity) {
        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userId);
        userOrder.setProductCode(productCode);
        userOrder.setQuantity(quantity);
        userOrderDao.save(userOrder);

//        System.out.println("wwww");


        EventLog eventLog = new EventLog();
        eventLog.setOperation("new order");
        eventLog.setOperator(userId);
        eventLogDao.save(eventLog);
    }

    @Transactional
    public void newOrderRollback(String userId, String productCode, int quantity) {
        UserOrder userOrder = new UserOrder();
        userOrder.setUserId(userId);
        userOrder.setProductCode(productCode);
        userOrder.setQuantity(quantity);
        userOrderDao.save(userOrder);

        EventLog eventLog = new EventLog();
        eventLog.setOperation("new order");
        eventLog.setOperator(userId);
        eventLogDao.save(eventLog);

        throw new RuntimeException("test jta rollback");
    }
}
